package com.konsung.ui.defineview;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.konsung.bean.CheckData;
import com.konsung.bean.MeasureDataBean;
import com.konsung.bean.PatientBean;
import com.konsung.healthfile.R;
import com.konsung.provide.ProviderReader;
import com.konsung.ui.adapter.SpinnerAdapter;
import com.konsung.util.IdCardUtil;
import com.konsung.util.KParamType;
import com.konsung.util.UiUtils;
import com.konsung.util.constant.GlobalConstant;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import uk.co.senab.photoview.PhotoView;

/**
 * 类功能：
 */

public class PhysicalExaminationView extends LinearLayout {
    @BindView(R.id.tv_serial)
    TextView tvSerial;
    @BindView(R.id.iv_close)
    ImageView ivClose;
    @BindView(R.id.sp_measure_time)
    Spinner spMeasureTime;
    @BindView(R.id.tv_how_mach)
    TextView tvHowMach;
    @BindView(R.id.btn_check_ecg)
    Button btnCheckEcg;
    @BindView(R.id.btn_print_report)
    Button btnPrintReport;
    @BindView(R.id.iv_report)
    ImageView ivReport;
    private PhysicalExaminationDrawable drawable;
    private SimpleDateFormat dateFormat;
    private WindowManager windowManager;
    private Context context;
    private List<MeasureDataBean> measureDataBeen;
    private PatientBean patientBean;
    private MeasureDataBean currentMeasureData;

    /**
     * 构造器
     * @param context 上下文
     * @param windowManager 窗口管理器
     * @param measureDataBeen 数据集合
     * @param patientBean 当前居民
     * @param drawable drawable
     */
    public PhysicalExaminationView(Context context, WindowManager windowManager,
            List<MeasureDataBean> measureDataBeen, PatientBean patientBean,
            PhysicalExaminationDrawable drawable) {
        super(context);
        this.windowManager = windowManager;
        this.measureDataBeen = measureDataBeen;
        this.patientBean = patientBean;
        this.context = context;
        this.drawable = drawable;
        currentMeasureData = new MeasureDataBean();
        dateFormat = UiUtils.getDateFormat(UiUtils.DateState.LONG);
        View inflate = inflate(context, R.layout.activity_health_report, null);
        addView(inflate);
        ButterKnife.bind(this);
        initMeasureTime();
        bindEvent();
        spMeasureTime.setPopupBackgroundDrawable(UiUtils.getDrawable(R.drawable.bg_drop_down_box));
        initViewData();
    }

    /**
     * 初始化测量时间列表
     */
    private void initMeasureTime() {
        tvHowMach.setText(String.valueOf(measureDataBeen.size()));
        String[] timeArr = new String[measureDataBeen.size()];
        for (int i = 0; i < measureDataBeen.size(); i++) {
            timeArr[i] = dateFormat.format(new Date(measureDataBeen.get(i).getMeasureTime()))
                    + getUpdateFlag(measureDataBeen.get(i).getUploadFlag());
        }
        SpinnerAdapter adapter = new SpinnerAdapter(context, timeArr);
        spMeasureTime.setAdapter(adapter);
    }

    /**
     * 初始化视图数据
     */
    private void initViewData() {
        initMeasureData();
        initEcgWaveData();
        if (currentMeasureData.getEcgHr() == GlobalConstant.INVALID_DATA) {
            btnCheckEcg.setEnabled(false);
        } else {
            btnCheckEcg.setEnabled(true);
        }
    }

    /**
     * 绑定点击事件
     */
    private void bindEvent() {
        spMeasureTime.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                currentMeasureData = measureDataBeen.get(position);
                initViewData();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    /**
     * 获取测量数据是否上穿
     * @param uploadFlag 上传状态
     * @return 上传状态
     */
    private String getUpdateFlag(boolean uploadFlag) {

        return uploadFlag ? UiUtils.getString(R.string.have_already_uploaded)
                : UiUtils.getString(R.string.haven_uploaded);
    }

    /**
     * 初始化测量数据
     */
    private void initMeasureData() {
        //赋值医生姓名
        CheckData checkData = ProviderReader.getCheckData(context);
        if (checkData != null && checkData.getCheckData() != null) {
            String empName = checkData.getCheckData().getEmpName();
            currentMeasureData.setDoctor(empName);
        }
        drawable.setData(currentMeasureData, patientBean);
        drawable.draw(new Canvas()); //先计算出Y轴高度
        int y = drawable.getY() + 100; //100为底部空隙  1280为图片宽度
        Bitmap bitmap = Bitmap.createBitmap(1280, y, drawable.getOpacity() != PixelFormat.OPAQUE ?
                Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bitmap);

        drawable.setBounds(0, 0, 1280, y);
        drawable.draw(canvas);
        ivReport.setMaxHeight(y);
        ivReport.setMaxWidth(1280);
        ivReport.setImageBitmap(bitmap);
    }

    /**
     * 初始化心电波形数据
     */
    private void initEcgWaveData() {

    }

    /**
     * 点击事件
     * @param view 点击的控件
     */
    @OnClick({R.id.iv_close, R.id.btn_check_ecg, R.id.btn_print_report})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_close:
                windowManager.removeView(this);
                break;
            case R.id.btn_check_ecg:
                final WindowManager.LayoutParams params = new WindowManager.
                        LayoutParams(WindowManager.LayoutParams.TYPE_PHONE);
                params.flags = WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM; //可以获取back事件
                LayoutInflater flater = (LayoutInflater) UiUtils.getContent().
                        getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                final View ecgView = flater.inflate(R.layout.pop_ecg_report, null);
                ReportView reportView = new ReportView();
                ButterKnife.bind(reportView, ecgView);
                initReportPatientData(reportView);
                initReportMeasureData(reportView);
                initReportEcgWave(reportView);
                windowManager.addView(ecgView, params);
                reportView.llReortView.setOnKeyListener(new View.OnKeyListener() {

                    @Override
                    public boolean onKey(View v, int keyCode, KeyEvent event) {
                        switch (keyCode) {
                            case KeyEvent.KEYCODE_BACK:
                                windowManager.removeView(ecgView);
                                return true;
                            default:
                                return false;
                        }
                    }
                });
                reportView.btnStopReport.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        windowManager.removeView(ecgView);
                    }
                });
                break;
            case R.id.btn_print_report:

                break;
            default:
                break;
        }
    }

    /**
     * 初始化病人信息
     * @param holder 体检报告控件容器
     */
    private void initReportPatientData(ReportView holder) {
        if (patientBean != null) {
            holder.tvReportAge.setText(patientBean.getAge() + UiUtils.getString(R.string.year));
            holder.tvReportName.setText(patientBean.getName());
            holder.tvReportIdcard.setText(UiUtils.getString(R.string.idcard_colon)
                    + patientBean.getIdcard());
            SimpleDateFormat dateFormat = UiUtils.getDateFormat(UiUtils.DateState.LONG);
            String measureTime = dateFormat.format(new Date(currentMeasureData.getMeasureTime()));
            holder.tvReportMeasureTime.setText(UiUtils.getString(R.string.measure_time_colon)
                    + measureTime);
            holder.tvReportSex.setText(IdCardUtil.getSexFormDB(patientBean.getSex()));
        }
    }

    /**
     * 初始化测量数据
     * @param holder 体检报告控件容器
     */
    private void initReportMeasureData(ReportView holder) {
        if (currentMeasureData != null) {
            String divide = UiUtils.getString(R.string.unit_divide);
            String ms = UiUtils.getString(R.string.unit_ms);
            String limit = UiUtils.getString(R.string.unit_limit);
            String mv = UiUtils.getString(R.string.unit_mv);
            String qtQtc = currentMeasureData.getQt() + divide + currentMeasureData.getQtc() + ms;
            String pQrsT = currentMeasureData.getPAxis() + divide + currentMeasureData.getQrsAxis()
                    + divide + currentMeasureData.getTAxis() + limit;
            holder.tvReportHr.setText(currentMeasureData.getTrendValue(KParamType.ECG_HR)
                    / GlobalConstant.INT_FACTOR + UiUtils.getString(R.string.health_unit_bpm));
            holder.tvReportPr.setText(currentMeasureData.getPr() + ms);
            holder.tvReportQrs.setText(currentMeasureData.getQrs()
                    + UiUtils.getString(R.string.unit_ms));
            holder.tvReportQtqtc.setText(qtQtc);
            holder.tvReportPQrsT.setText(pQrsT);
            //协议上的单位是0.01mv。
            float rv5 = (float) currentMeasureData.getRv5() / GlobalConstant.FACTOR;
            float sv1 = (float) currentMeasureData.getSv1() / GlobalConstant.FACTOR;
            String rv5Sv1 = String.format(Locale.ENGLISH, "%.2f", rv5) + divide
                    + String.format(Locale.ENGLISH, "%.2f", sv1) + mv;
            holder.tvReportRv5Sv1.setText(rv5Sv1);
            holder.tvReportRv5Sv1Add.setText(String.format(Locale.ENGLISH, "%.2f", rv5 + sv1));
            holder.tvReportResult.setText(currentMeasureData.getEcgDiagnoseResult());
        }
    }

    /**
     * 初始化心电波形
     * @param holder 体检报告控件容器
     */
    private void initReportEcgWave(ReportView holder) {
        //获取全屏的宽高
        DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
        final int width = displayMetrics.widthPixels;
        final int height = displayMetrics.heightPixels;
        EcgReportDrawable drawable = new EcgReportDrawable(currentMeasureData, height, width);
        // 1280屏幕宽度，575控件高度
        Bitmap bitmap = Bitmap.createBitmap(1280, 575, drawable.getOpacity() != PixelFormat.OPAQUE ?
                Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, 1280, 575);
        drawable.draw(canvas);
        holder.imgReport.setImageBitmap(bitmap);
    }

    /**
     * 体检报告控件容器
     */
    public class ReportView {

        @BindView(R.id.ll_report_view)
        LinearLayout llReortView;
        @BindView(R.id.tv_report_name)
        TextView tvReportName;
        @BindView(R.id.tv_report_sex)
        TextView tvReportSex;
        @BindView(R.id.tv_report_age)
        TextView tvReportAge;
        @BindView(R.id.tv_report_idcard)
        TextView tvReportIdcard;
        @BindView(R.id.tv_report_measure_time)
        TextView tvReportMeasureTime;
        @BindView(R.id.btn_stop_report)
        Button btnStopReport;
        @BindView(R.id.tv_report_hr)
        TextView tvReportHr;
        @BindView(R.id.tv_report_pr)
        TextView tvReportPr;
        @BindView(R.id.tv_report_qrs)
        TextView tvReportQrs;
        @BindView(R.id.tv_report_qtqtc)
        TextView tvReportQtqtc;
        @BindView(R.id.tv_report_pQrsT)
        TextView tvReportPQrsT;
        @BindView(R.id.tv_report_rv5Sv1)
        TextView tvReportRv5Sv1;
        @BindView(R.id.tv_report_RV5SV1Add)
        TextView tvReportRv5Sv1Add;
        @BindView(R.id.tv_report_result)
        TextView tvReportResult;
        @BindView(R.id.img_report)
        PhotoView imgReport;
    }
}
